package com.JUC.cha08;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 手写自旋锁，不用synchronized，使用CAS思想
 */
public class spinLockDemo {


    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();

        System.out.println("---- come in thread " + Thread.currentThread().getName());
        while (!atomicReference.compareAndSet(null, thread)) {// 期望值为空
        }
    }

    public void unLock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println("---- task over thread " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {

        spinLockDemo spinLockDemo = new spinLockDemo();

        new Thread(() -> {
            spinLockDemo.lock();
            // 暂停5秒钟线程
            try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
            spinLockDemo.unLock();

        }, "A").start();
        
        // 暂停几秒钟线程,保证线程A优先运行于线程B
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            spinLockDemo.lock();
            spinLockDemo.unLock();
        }, "B").start();
        
    }

}
